import {
  type Ref,
  ref,
  computed,
  h,
  Fragment,
  onBeforeUnmount,
  shallowRef,
  onMounted
} from "vue";
import type { PlusColumn, FieldValues, OptionsRow } from "plus-pro-components";
import { getUploadUrl } from "@/utils/utils";
import { ElUpload, ElButton, ElImage } from "element-plus";
import { getToken, formatToken } from "@/utils/auth";
import { message } from "@/utils/message";
import { getNews, updateNews } from "@/api/zhaoyuan";
//编辑器
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import type { IDomEditor, InsertFnType } from "@wangeditor/editor";
const { token } = getToken();
export function useForm(pageEnums: Ref<{ [key: string]: OptionsRow[] }>) {
  const formRules = {
    name: [
      {
        required: true,
        message: "请输入名称"
      }
    ]
  };
  // 编辑器实例，必须用 shallowRef
  const editorRef = shallowRef();
  const handleCreated = editor => {
    editorRef.value = editor;
  };
  const formColumns: PlusColumn[] = [
    {
      label: "名称",
      prop: "title"
    },
    {
      label: "分类",
      prop: "category",
      valueType: "select",
      options: computed(() => pageEnums.value.newsCategoryList)
    },
    {
      label: "作者",
      prop: "author"
    },
    {
      label: "是否发布",
      prop: "isPublished",
      valueType: "switch"
    },

    {
      label: "状态",
      prop: "status",
      valueType: "radio",
      options: computed(() => pageEnums.value.newsStatusList)
    },
    {
      label: "内容",
      prop: "content",
      renderField(value, onChange) {
        return h("div", { style: "border: 1px solid #ccc" }, [
          h(Toolbar, {
            style: "border-bottom: 1px solid #ccc",
            editor: editorRef.value,
            defaultConfig: {},
            mode: "default"
          }),
          h(Editor, {
            style: "height: 350px; overflow-y: hidden;",
            modelValue: value,
            defaultConfig: {
              placeholder: "请输入内容...",
              MENU_CONF: {
                uploadImage: {
                  server: getUploadUrl,
                  maxFileSize: 20 * 1024 * 1024, // 5M
                  headers: {
                    Authorization: formatToken(token)
                  },
                  fieldName: "file",
                  allowedFileTypes: ["image/png", "image/jpg", "image/jpeg"],
                  // 自定义插入图片
                  customInsert(res: any, insertFn: InsertFnType) {
                    // TS 语法
                    // customInsert(res, insertFn) {                  // JS 语法
                    // res 即服务端的返回结果

                    // 从 res 中找到 url alt href ，然后插入图片
                    insertFn(res.url, res.fileName, res.url);
                  }
                },
                uploadVideo: {
                  server: getUploadUrl,
                  maxFileSize: 20 * 1024 * 1024, // 5M
                  headers: {
                    Authorization: formatToken(token)
                  },
                  fieldName: "file",
                  allowedFileTypes: ["video/*"],
                  // 自定义插入图片
                  customInsert(res: any, insertFn: InsertFnType) {
                    insertFn(res.url, res.fileName, res.url);
                  }
                }
              }
            },
            mode: "default",
            onOnCreated: handleCreated,
            onOnChange: (editor: IDomEditor) => {
              onChange(editor.getHtml());
            }
          })
        ]);
      }
    },
    {
      label: "缩略图",
      prop: "thumbnail_",
      width: 100,
      valueType: "img",
      renderField(value, onChange) {
        value = typeof value === "string" ? value : "";
        return h(Fragment, [
          h(
            ElUpload,
            {
              action: getUploadUrl,
              multiple: false,
              "file-list": [{ url: value, name: value.split("/").pop() }],
              headers: {
                Authorization: formatToken(token)
              },
              onSuccess: (response, file) => {
                console.log("上传成功", response, file);
                onChange(response.url);
              },
              onError: (error, file) => {
                message("上传失败！", { type: "error" });
              }
            },
            () => h(ElButton, () => "点击上传")
          )
        ]);
      }
    },
    {
      label: "封面图",
      prop: "coverImage_",
      width: 100,
      valueType: "img",
      renderField(value, onChange) {
        value = typeof value === "string" ? value : "";
        return h(Fragment, [
          h(
            ElUpload,
            {
              action: getUploadUrl,
              multiple: false,
              "file-list": [{ url: value, name: value.split("/").pop() }],
              headers: {
                Authorization: formatToken(token)
              },
              onSuccess: (response, file) => {
                console.log("上传成功", response, file);
                onChange(response.url);
              },
              onError: (error, file) => {
                message("上传失败！", { type: "error" });
              }
            },
            () => h(ElButton, () => "点击上传")
          )
        ]);
      }
    },
    {
      label: "媒体文件",
      prop: "mediaList_",
      width: 100,
      renderField(value, onChange) {
        const fileList = Array.isArray(value) ? value : [];
        return h(Fragment, [
          h(
            ElUpload,
            {
              action: getUploadUrl,
              multiple: true,
              "file-list": fileList.map(url => ({
                url,
                name: url.split("/").pop() || "未知文件"
              })),
              limit: 9,
              headers: {
                Authorization: formatToken(token)
              },
              onSuccess: (response, file) => {
                console.log(value);
                console.log("上传成功", response, file);
                // 确保 value 是数组
                const updatedValue = Array.isArray(value)
                  ? [...value, response.url]
                  : [response.url];
                onChange(updatedValue);
              },
              onError: (error, file) => {
                message("上传失败！", { type: "error" });
              }
            },
            () => h(ElButton, () => "点击上传")
          )
        ]);
      }
    }
  ];
  const formTitle = ref("");
  const formId = ref<number>(0);
  const formVisible = ref(false);
  const formValues = ref<FieldValues>({
    isPublished: true
  });

  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
  });
  const formOpen = (title = "新增", row: any = {}) => {
    if (title == "修改") {
      formId.value = row.id;
      getNews(row.id).then(res => {
        console.log(res);
        formValues.value = res;
      });
    } else {
      formId.value = 0;
      formValues.value = {
        isPublished: true
      };
    }
    formTitle.value = title;
    formVisible.value = true;
  };

  return {
    formRules,
    formColumns,
    formVisible,
    formValues,
    formOpen,
    formTitle,
    formId
  };
}
